<?php
/** MY_html_helper
	* 
	* @package Pharmacy Intervention 
	* @subpackage Helpers
	* @category HTML
	* @author Ray Nowell
	* 
	* This helper is designed to provided a central location for commonly used html sections of code.
	* Primarily created this to provide a common location for all grid javascript functions
	*/  

	/*
	 * get_grid_doc_ready_javascript:	
	 *	This function returns javascript loaded in the doc ready function of JQuery.	It preps the page to handle the 
	 *	the buttons add, copy, view, delete 
	 *	
	 *	$use_copy : means that the copy button will be used
	*/
	function get_grid_doc_ready_javascript($use_copy = false)
	{
			$ret_val = '$("#_gridAddTop").click(function() 
									{
										popup_add();
										return false;
									});
									
									$("#_gridViewTop").click(function() 
									{
										var numberChecked = countChecked();
										if (numberChecked <=0) 
											return false;
										
										viewSelectedRecords();
										return true;
									});
									
									$("#_gridDeleteTop").click(function() 
									{
										var numberChecked = countChecked();
										if (numberChecked <=0) 
											return false;
										
										var pluralText = numberChecked == 1 ? "" : "s";
										var confirmMessage = "You are about to delete " + numberChecked + " record" + pluralText + ".	\nClick ok to confirm this action.";
										if (!confirm(confirmMessage))
											return false;

										deleteSelectedRecords();
										
										return true;
									});
									
									$("#_gridCopyTop").click(function() 
									{
										var numberChecked = countChecked();
										if (numberChecked <=0) 
											return false;
										
										copySelectedRecords();
										return true;	
									});
									
									$("#_chkMaster").click(function() 
									{
										var checkAll = ($(this).is(":checked"))
										$(".GridCheckbox").each( function() 
											{
												if (checkAll != $(this).is(":checked"))
												{					 
													$(this).attr("checked", checkAll);
													var rowVar = $(this).parent().parent();
												var className = rowVar.attr("class");
												if ($(this).is(":checked"))
										 			rowVar.attr("class",className + "Selected");
													else
													rowVar.attr("class",className.replace("Selected",""));
												}
											});
										
										if (isChangeGridButtonStateRequired())
									changeGridButtonState(countChecked() == 0);
										return true;
									});
								 
									
									$(".GridCheckbox").click(function() 
										{
										//See need to change the row to selected
										var rowVar = $(this).parent().parent();
										var className = rowVar.attr("class");
										if ($(this).is(":checked"))
										 	rowVar.attr("class",className + "Selected");
										else
											rowVar.attr("class",className.replace("Selected",""));
										
										//See need to change the button states
											if (isChangeGridButtonStateRequired())
												changeGridButtonState(countChecked() == 0);
											return true;
										});
										
										//Needs to be called in case of refresh:
										if (isChangeGridButtonStateRequired())
											changeGridButtonState(countChecked() == 0);
										//Also need to be called in case of a refresh to set classes on remember checks
									 //Currently, only Firefox does this 
										if (countChecked() > 0)
										{
										$(".GridCheckbox").each( function() 
											{
												if ($(this).is(":checked"))
												{					 
													var rowVar = $(this).parent().parent();
												var className = rowVar.attr("class");
										 		rowVar.attr("class",className + "Selected");
												}
											});
										}
									';
		return $ret_val;
	}

	/*
	 *	 
	 */
	function get_grid_functions($controller_name, $popupHeight, $popupWidth)
	{
		$view_selected_records_from_grid = 'function viewSelectedRecords()
											{
												var viewIds = new Array();
												var arrayCounter = 0;
												$(".GridCheckbox").each( function() 
																				{
																					if ($(this).is(":checked"))
																					{					 
																			 			viewIds[arrayCounter] = $(this).attr("name").replace("_chkIntervention","");
																			 			arrayCounter++;
																					}
																		});
																		var viewUrl = "'.site_url($controller_name.'/edit').'/4/" + viewIds.join("/");	
																		var popupLeft = parseInt((screen.availWidth/2) - ('.$popupWidth.'/2));
													var popupTop = parseInt((screen.availHeight/2) - ('.$popupHeight.'/2));
														window.open(viewUrl,\'popup\',\'width=\' + '.$popupWidth.' + \',height=\' + '.$popupHeight.' + \',scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=\' + popupLeft + \',top=\' + popupTop + \'\');
														window.status = window.status=("Connecting...");
														return false;
																		
												
											}';
		$delete_selected_records_from_grid = 'function deleteSelectedRecords()
												{
													var deleteIds = new Array();
																			var arrayCounter = 0;
													$(".GridCheckbox").each( function() 
																				{
																					if ($(this).is(":checked"))
																					{					 
																			 			deleteIds[arrayCounter] = $(this).attr("name").replace("_chkIntervention","");
																			 			arrayCounter++;
																					}
																		});
																		var deleteUrl = "'.site_url($controller_name.'_list/delete').'/" + deleteIds.join("/");
																		this.location.href = deleteUrl;
																		window.status = window.status=("Connecting...");
												}'; 
		$is_change_grid_button_state_required = 'function isChangeGridButtonStateRequired()
																 {
																 
																	var itemsAreChecked = countChecked() > 0;
																	var imageSrcText = $("#_gridViewTop").attr("src");
																	var isDisabled = imageSrcText.indexOf("disabled") > 0;
																	var retValue = false
																																		
																	retValue = (itemsAreChecked &&	isDisabled) ||	(!itemsAreChecked &&	!isDisabled)
																	return retValue; 
																 }
																 '
		;
		 
		$change_grid_button_state = 'function changeGridButtonState(isDisabled)
																 {
																	$(".GridButton").each( function() 
											{					 var src = $(this).attr("src");
																	var replaceSource = isDisabled ? ".png" : "_disabled" ;
																	var replaceWith = isDisabled ? "_disabled.png" : "" ;
																	var disabledAttr = isDisabled ? "disabled" : "";
																	src = src.replace(replaceSource,replaceWith);
																	$(this).attr("src", src);																	
																	$(this).attr("disabled", disabledAttr);
																	});
																	
															 	};
																';
		
		$checkbox_checked_js = 'function countChecked() 
														{
															var n = $(".GridCheckbox:checked").length;
															return n;
														};';
		
		$popup_add_code_js = 'function popup_add()
													{
														var popupLeft = parseInt((screen.availWidth/2) - ('.$popupWidth.'/2));
																						var popupTop = parseInt((screen.availHeight/2) - ('.$popupHeight.'/2));
																						window.open(\''.site_url($controller_name.'/add').'\',\'popup\',\'width=\' + '.$popupWidth.' + \',height=\' + '.$popupHeight.' + \',scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=\' + popupLeft + \',top=\' + popupTop + \'\');
																						return false;
													}
													';
		
		//If user clicks on a link from a grid that will edit a single record
		$popup_edit_single_js = 'function popup_edit_single(recordId)
													{
														var popupLeft = parseInt((screen.availWidth/2) - ('.$popupWidth.'/2));
																						var popupTop = parseInt((screen.availHeight/2) - ('.$popupHeight.'/2));
																						window.open(\''.site_url($controller_name.'/edit/\' + recordId').',\'popup\',\'width=\' + '.$popupWidth.' + \',height=\' + '.$popupHeight.' + \',scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=\' + popupLeft + \',top=\' + popupTop + \'\');
																						return false;
													}';
		$ret_val	=	$view_selected_records_from_grid.$delete_selected_records_from_grid.$is_change_grid_button_state_required.$change_grid_button_state.$checkbox_checked_js.$popup_add_code_js.$popup_edit_single_js;
		return $ret_val;		
	}
	
	
	/*
	 * When a pop-up is loaded in "View Mode" users can Navigate through the different records with the navigation javascript
	 * The script returned here is the function called to navigate to the first, previous, next and last records 
	 */
	function get_navigation_doc_ready_javascript()
	{
		$ret_val = '$(".NavLink").click(function(){
										if (!confirmNavigation())
											return false;
										navigateRecord($(this).attr("title").replace("Move",""));
										return false; 
									});';
		return $ret_val;
	}
	 /*
	 * When a pop-up is loaded in "View Mode" users can Navigate through the different records with the navigation javascript
	 * this routine returns the jQuery script to be loaded in the document ready function
	 */
	function get_navigation_functions($nav_url, $previous_segment, $next_segment,$total_segments)
	{
		$retVal = 'function navigateRecord(direction)
								{
								var NAV_URL = \''.$nav_url.'\';
								var PREV_ID = '.$previous_segment.';
								var NEXT_ID = '.$next_segment.';
								var FIRST_ID = "4";
								var LAST_ID = '.$total_segments.';
								var replaceString = "";
								switch(direction)
								{
									case "First":
											replaceString = FIRST_ID;
											break;
									case "Previous":
										replaceString = PREV_ID;
											break;
									case "Next":
											replaceString = NEXT_ID;
											break;
									case "Last":
											replaceString = LAST_ID;
											break;					
									default:
											window.alert("bad command");
								}
								
								var new_location = NAV_URL.replace("|",replaceString);
								if (new_location.toLowerCase() != this.location.toString().toLowerCase())
									this.location.replace(new_location);	 
							}'; 
		return $retVal;
	}
	
	/*
	 * Returns javascript used to check concurrency on save 
	 * 
	 */
	function get_save_javascript($controller_name)
	{
		$retVal	=	'$(\'#_save\').click(function() {
						var pathname = window.location.pathname;
	 					var parsedPathname = pathname.substr(pathname.length - 3, 3);
	 					if (parsedPathname == \'add\') //It\'s always ok to add
	 						return true;
	 	
	 					//Editing a record.  Check to see if it has been modified
	 					var myId = $(\'#id\').val();
						if (record_is_modified(\''.$controller_name.'\', myId))
						{
							if (!confirmOverwrite())
							{
								window.location.reload();
								return false;
							}
						}
						});';
		
		return $retVal;
	}
	
	/*
	 * Returns the markup required to display the navigation bar
	 */
	function get_navigation_markup($base_url, $current_record_number, $total_records)
	{
		$ret_val = '<br class="clear" />';
				
				$direction = '';
				for ( $counter = 1; $counter <= 4; $counter++) 
				{
					switch ($counter) 
					{
						case 1:
							$direction = 'First';
							break;
						case 2:
							$direction = 'Previous';
							break;
						case 3:
							$direction = 'Next';
							break;
						case 4:
							$direction = 'Last';
							break;
					}
					$edit_link_atts = array('title' => 'Move'.$direction,
																	'class' => 'NavLink',
																	'disabled' => 'disabled'
					);
					
					$link_text = anchor('requirements','<image border = 0 alt = "Move " src="'.$base_url.'/images/move_'.strtolower($direction).'.png"/>',$edit_link_atts);;
					$link_text = str_replace(site_url().'/requirements','#',$link_text);
					$ret_val .= $counter == 3 ? 'Record '.$current_record_number.' of '.$total_records : '' ;
					$ret_val .= $link_text; 
				}
					return $ret_val;
	}
	
	
	/**
	* Returns the Table Template used for all grids
	* 
	* @access public 
	* @return string */ 
	function set_table_template()
	{
		$tmpl = array (
										'table_open'          => '<table class="grid" border="0" cellpadding="4" cellspacing="0">',

										'heading_row_start'   => '<tr class="gridHeader">',
										'heading_row_end'     => '</tr>',
										'heading_cell_start'  => '<th>',
										'heading_cell_end'    => '</th>',

										'row_start'           => '<tr class="gridRow">',
										'row_end'             => '</tr>',
										'cell_start'          => '<td>',
										'cell_end'            => '</td>',

										'row_alt_start'       => '<tr class="gridAlternatingRow">',
										'row_alt_end'         => '</tr>',
										'cell_alt_start'      => '<td>',
										'cell_alt_end'        => '</td>',

										'table_close'         => '</table>'
									);
									
		return $tmpl;
	}
	
	/** 
	 * Takes an array_result and turns it in an array
	 * @access public 
	 * @return */
	function set_lookup($lookup_array,$field_name_key,$field_name_value,$add_empty_value = false)
	{
		$return_array = array();

		if ($add_empty_value)
			$return_array[-1] = '';

		foreach ($lookup_array as $row)
			$return_array[$row[$field_name_key]] = $row[$field_name_value]; 

		return $return_array;
	}
	
	function format_percent($passed_number)
	{
		$ret_val = (round($passed_number * 1000))/10;
		return $ret_val.'%';
	}
	
	//http://smashscripts.blogspot.com/2008/07/php-format-currency-function.html
	//constants defined in constants.php
	function format_currency($amount, $NumDigitsAfterDecimal = 2, $IncludeLeadingDigit = false, $UseParensForNegativeNumbers = true, $GroupDigits = true)
	{
	
		// export the values returned by localeconv into the local scope
		if (function_exists("localeconv")) extract(localeconv());
		
		// set defaults if locale is not set
		if (empty($currency_symbol)) $currency_symbol = DEFAULT_CURRENCY_SYMBOL;
		if (empty($mon_decimal_point)) $mon_decimal_point = DEFAULT_MON_DECIMAL_POINT;
		if (empty($mon_thousands_sep)) $mon_thousands_sep = DEFAULT_MON_THOUSANDS_SEP;
		if (empty($positive_sign)) $positive_sign = DEFAULT_POSITIVE_SIGN;
		if (empty($negative_sign)) $negative_sign = DEFAULT_NEGATIVE_SIGN;
		if (empty($frac_digits) || $frac_digits == CHAR_MAX) $frac_digits = DEFAULT_FRAC_DIGITS;
		if (empty($p_cs_precedes) || $p_cs_precedes == CHAR_MAX) $p_cs_precedes = DEFAULT_P_CS_PRECEDES;
		if (empty($p_sep_by_space) || $p_sep_by_space == CHAR_MAX) $p_sep_by_space = DEFAULT_P_SEP_BY_SPACE;
		if (empty($n_cs_precedes) || $n_cs_precedes == CHAR_MAX) $n_cs_precedes = DEFAULT_N_CS_PRECEDES;
		if (empty($n_sep_by_space) || $n_sep_by_space == CHAR_MAX) $n_sep_by_space = DEFAULT_N_SEP_BY_SPACE;
		if (empty($p_sign_posn) || $p_sign_posn == CHAR_MAX) $p_sign_posn = DEFAULT_P_SIGN_POSN;
		if (empty($n_sign_posn) || $n_sign_posn == CHAR_MAX) $n_sign_posn = DEFAULT_N_SIGN_POSN;
		
		// check $NumDigitsAfterDecimal
		if ($NumDigitsAfterDecimal > -1)
		$frac_digits = $NumDigitsAfterDecimal;
		
		// check $UseParensForNegativeNumbers
		if ($UseParensForNegativeNumbers == -1) {
		$n_sign_posn = 0;
		if ($p_sign_posn == 0) {
		if (DEFAULT_P_SIGN_POSN != 0)
		$p_sign_posn = DEFAULT_P_SIGN_POSN;
		else
		$p_sign_posn = 3;
		}
		} elseif ($UseParensForNegativeNumbers == 0) {
		if ($n_sign_posn == 0)
		if (DEFAULT_P_SIGN_POSN != 0)
		$n_sign_posn = DEFAULT_P_SIGN_POSN;
		else
		$n_sign_posn = 3;
		}
		
		// check $GroupDigits
		if ($GroupDigits == -1) {
		$mon_thousands_sep = DEFAULT_MON_THOUSANDS_SEP;
		} elseif ($GroupDigits == 0) {
		$mon_thousands_sep = "";
		}
		
		// start by formatting the unsigned number
		$number = number_format(abs($amount),
		$frac_digits,
		$mon_decimal_point,
		$mon_thousands_sep);
		
		// check $IncludeLeadingDigit
		if ($IncludeLeadingDigit == 0) {
		if (substr($number, 0, 2) == "0.")
		$number = substr($number, 1, strlen($number)-1);
		}
		if ($amount < 0) {
		$sign = $negative_sign;
		
		// "extracts" the boolean value as an integer
		$n_cs_precedes = intval($n_cs_precedes == true);
		$n_sep_by_space = intval($n_sep_by_space == true);
		$key = $n_cs_precedes . $n_sep_by_space . $n_sign_posn;
		} else {
		$sign = $positive_sign;
		$p_cs_precedes = intval($p_cs_precedes == true);
		$p_sep_by_space = intval($p_sep_by_space == true);
		$key = $p_cs_precedes . $p_sep_by_space . $p_sign_posn;
		}
		$formats = array(
		
		// currency symbol is after amount
		
		// no space between amount and sign
		'000' => '(%s' . $currency_symbol . ')',
		'001' => $sign . '%s ' . $currency_symbol,
		'002' => '%s' . $currency_symbol . $sign,
		'003' => '%s' . $sign . $currency_symbol,
		'004' => '%s' . $sign . $currency_symbol,
		
		// one space between amount and sign
		'010' => '(%s ' . $currency_symbol . ')',
		'011' => $sign . '%s ' . $currency_symbol,
		'012' => '%s ' . $currency_symbol . $sign,
		'013' => '%s ' . $sign . $currency_symbol,
		'014' => '%s ' . $sign . $currency_symbol,
		
		// currency symbol is before amount
		
		// no space between amount and sign
		'100' => '(' . $currency_symbol . '%s)',
		'101' => $sign . $currency_symbol . '%s',
		'102' => $currency_symbol . '%s' . $sign,
		'103' => $sign . $currency_symbol . '%s',
		'104' => $currency_symbol . $sign . '%s',
		
		// one space between amount and sign
		'110' => '(' . $currency_symbol . ' %s)',
		'111' => $sign . $currency_symbol . ' %s',
		'112' => $currency_symbol . ' %s' . $sign,
		'113' => $sign . $currency_symbol . ' %s',
		'114' => $currency_symbol . ' ' . $sign . '%s');
		
		// lookup the key in the above array
		return sprintf($formats[$key], $number);
	}
	
	
/* End of file MY_html_helper.php */
/* Location: ./system/application/helpers/MY_html_helper.php */
